<script setup lang="ts">
//@ts-nocheck    解决ts类型报红
import { ref, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { Right, Back } from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  label: {
    type: String,
    default: "label",
  },
  nodeKey: {
    type: String,
    default: "id",
  },
  fromData: {
    type: Array,
    default: () => [],
  },
  toData: {
    type: Array,
    default: () => [],
  },
  defaultProps: {
    type: Object,
    default: {
      label: "label",
      value: "id",
      disabled: "disabled",
    },
  },
  // 是否树结构
  three: {
    type: Boolean,
    default: true,
  },
});

// 定义emit
const emit = defineEmits(["checkVal", "change", "modelValue"]);
const treeRef = ref();

// 右侧数据
const toData = ref([]);

// 去右边
const threeToRight = () => {
  const checkNodes = treeRef.value.getCheckedNodes(false, false);
  // 过滤部门本身
  const newArr = toData.value.concat(
    checkNodes.filter((t: any) => t.type == 1)
  );

  let obj = {};
  let peon = newArr.reduce((cur, next) => {
    obj[next[props.nodeKey]]
      ? ""
      : (obj[next[props.nodeKey]] = true && cur.push(next));
    return cur;
  }, []); // 设置cur默认类型为数组，并且初始值为空的数组
  console.log(peon, "peon");

  toData.value = peon;
  toData.value.forEach((t) => (t.rightActive = false));
  treeRef.value.setCheckedKeys([], false);
  checkVal();

  toRightDg(props.fromData);
};

// 去左边
const threeToLeft = async () => {
  for (var i = 0; i < toData.value.length; i++) {
    if (toData.value[i].rightActive) {
      toData.value[i].rightActive = false;
      toData.value.splice(i, 1);
      i -= 1;
    }
  }

  checkVal();
  // console.log(toData.value, 'toData.value')

  toLeftDg(props.fromData, false);
  treeRef.value.setCheckedKeys([], false);
};

// 去右边 递归禁用
const toRightDg = (arr: any) => {
  arr.forEach((left: any) => {
    toData.value.forEach((right) => {
      if (left.children?.length > 0) {
        toRightDg(left.children);
      }

      if (left[props.nodeKey] == right[props.nodeKey]) {
        // 已选的不可重复勾选
        left.disabled = true;
      }
    });
  });
};

// 去左边 递归禁用
const toLeftDg = (arr: any) => {
  console.log(toData.value.length, "ata.value");

  if (toData.value.length == 0) {
    console.log("ces1", props.fromData);
    arr.forEach((left: any) => {
      if (left.children) {
        toLeftDg(left.children);
      } else {
        console.log(left, "left");

        if (!left.parentId) {
          left.disabled = true;
        } else {
          left.disabled = false;
        }
      }

      // if (left[props.nodeKey] != right[props.nodeKey]) {
      //   // 已选的不可重复勾选
      //   left.disabled = false;
      // }
    });
  } else {
    arr.forEach((left: any) => {
      toData.value.forEach((right) => {
        if (left.children) {
          toLeftDg(left.children);
        }

        if (left[props.nodeKey] != right[props.nodeKey]) {
          // 已选的不可重复勾选
          left.disabled = false;
        }
      });
    });
  }
};
/**
 * 平顺结构处理数据-------------------------------------------->
 */
// 左侧点击复选框时

// 去右边
const toRight = () => {
  let peon = props.fromData.reduce((cur, next) => {
    next.leftActive ? cur.push(next) : "";
    return cur;
  }, []); // 设置cur默认类型为数组，并且初始值为空的数组

  toData.value = peon;
  // 勾选为false初始值
  toData.value.forEach((t) => (t.rightActive = false));
  // 禁用左侧已选择数据
  props.fromData.forEach((left) => {
    toData.value.forEach((right) => {
      if (left[props.nodeKey] == right[props.nodeKey]) {
        left.disabled = true;
      }
    });
  });
  checkVal();
};

// 去左边
const toleft = () => {
  for (var i = 0; i < toData.value.length; i++) {
    if (toData.value[i].rightActive) {
      toData.value[i].rightActive = false;
      const obj = props.fromData.find(
        (t) => t[props.nodeKey] == toData.value[i][props.nodeKey]
      );

      if (!obj) return console.error("未找到:toleft");
      obj.leftActive = false;
      obj.disabled = false;
      toData.value.splice(i, 1);
      i -= 1;
    }
  }

  // 恢复状态 选择状态 toData

  // 初始左侧状态
  if (toData.value.length <= 0) {
    props.fromData.forEach((t) => {
      t.leftActive = false;
      t.disabled = false;
    });
  }
  checkVal();
};

// 判断是否禁用去右边
const leftBtnDisabled = computed(() => {
  if (props.three) return false;
  const leftActive = props.fromData.some((t) => t.leftActive);
  const disabled = props.fromData.every((t) => t.disabled);
  return !leftActive || disabled;
});

// 判断是否禁用去左边
const rightBtnDisabled = computed(() => {
  if (props.three) return false;
  return (
    !toData.value.some((t) => t.rightActive == true) || toData.value.length <= 0
  );
});

// 回显
onMounted(() => {
  console.log(props.toData, "props.toData--");

  if (props.toData?.length > 0) {
    sessionStorage.setItem("toData", JSON.stringify(props.toData));
    toData.value = JSON.parse(sessionStorage.getItem("toData"));

    if (props.three) {
      const arr = toData.value.map((t) => t.id);
      treeRef.value.setCheckedNodes(arr, false);
      toRightDg(props.fromData);
      // toData.value.forEach((t) => (t.rightActive = false))
      // treeRef.value.setCheckedKeys([], false)
      // threeToRight()
    } else {
      // 勾选为false初始值
      toData.value.forEach((t) => (t.rightActive = false));
      // 禁用左侧已选择数据
      props.fromData.forEach((left) => {
        toData.value.forEach((right) => {
          console.log(
            left[props.nodeKey],
            right[props.nodeKey],
            "left[props.nodeKey]"
          );
          if (left[props.nodeKey] == right[props.nodeKey]) {
            left.disabled = true;
            left.leftActive = true;
          }
        });
      });

      checkVal();
    }
  }
});

// 返回父组件
const checkVal = () => {
  emit(
    "change",
    toData.value.map((t) => t[props.nodeKey])
  );
  emit(
    "update:modelValue",
    toData.value.map((t) => t[props.nodeKey])
  );
  emit("changeSlot", toData.value);
};

const aaa = (arr) => {
  arr.forEach((t) => {
    if (t.children && t.children.length > 0) {
      aaa(t.children);
      t.disabled = false;
    } else {
      if (!t.parentId) t.disabled = true;
    }
  });
};

nextTick(() => aaa(props.fromData));

watch(
  () => props.fromData,
  () => {
    aaa(props.fromData);
  }
);

defineExpose({
  toData,
});
</script>
// 封装组件
<template>
  <el-card class="treeTransfer" ref="pTreeTransRef">
    <!-- 左边 -->
    <div class="leftTree">
      <div class="list">
        <p class="left_title title">用户列表</p>
        <!-- 搜索 -->
        <div class="left_input">
          <slot name="left_input" />
        </div>
        <el-tree
          v-if="props.three"
          ref="treeRef"
          :data="props.fromData"
          show-checkbox
          :node-key="props.nodeKey"
          highlight-current
          :props="props.defaultProps"
        />

        <template v-else>
          <div
            class="right_item"
            :class="['item', { rightActive: item.rightActive }]"
            v-for="(item, index) in props.fromData"
            :key="index"
          >
            <div class="right_item_main">
              <input v-show="false" v-model="item.disabled" />
              <el-checkbox
                :disabled="item.disabled"
                style="width: 15.375rem"
                v-model="item.leftActive"
                >{{ item[props.defaultProps.label] }}</el-checkbox
              >
              <slot class="leftItem" name="leftItem" :item="item" />
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- 中间按钮 -->
    <div class="btnDiv">
      <div class="mb20" @click="props.three ? threeToRight() : toRight()">
        <el-button :disabled="leftBtnDisabled" :icon="Right" circle />
      </div>
      <div class="mt20" @click="props.three ? threeToLeft() : toleft()">
        <el-button :icon="Back" circle :disabled="rightBtnDisabled" />
      </div>
    </div>
    <!-- 右边 -->
    <div class="rightTree">
      <div class="list">
        <p class="left_title title">已选列表</p>
        <!-- 搜索 -->
        <div class="left_input">
          <slot name="right_input" />
        </div>

        <div
          class="right_item"
          :class="['item', { rightActive: item.rightActive }]"
          v-for="(item, index) in toData"
          :key="index"
          @click="checkNode(item)"
        >
          <div class="right_item_main">
            <el-checkbox style="width: 15.375rem" v-model="item.rightActive">{{
              item[props.defaultProps.label]
            }}</el-checkbox>
            <slot class="rightItem" name="rightItem" :item="item" />
          </div>
        </div>
        <el-empty description="description" v-if="toData.length == 0" />
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.treeTransfer ::v-deep .el-card__body {
  display: flex;
  justify-content: space-around;
}
.treeTransfer {
  .rightTree,
  .leftTree {
    .left_title {
    }
    .list {
      width: 12.5rem;
      height: 22.75rem;
    }
  }
  .btnDiv {
    margin-top: 5.125rem;
  }
}

.right_item_main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .rightItem {
    margin-left: 50px;
  }
}
</style>
